import { Component, OnInit, ViewChild,ElementRef } from '@angular/core';
import * as ECharts from 'echarts';
import { weekday } from '../../../../../environments/environment';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import BScroll from 'better-scroll';

@Component({
  selector: 'app-transaction-statistics',
  templateUrl: './transaction-statistics.page.html',
  styleUrls: ['./transaction-statistics.page.scss'],
})
export class TransactionStatisticsPage implements OnInit {
  @ViewChild('chart',
    { read: false, static: false }
  ) chart: any;

  @ViewChild('picChart',
    { read: false, static: false }
  ) picChart: any;

  @ViewChild('monthScroll',{static:true}) monthScroll: ElementRef;

  dateType: any = 'Month';

  dateTypes: any[] = [
    {
      type: 'Year',
      num: 1
    },
    {
      type: 'Month',
      num: 2
    }
  ];
  months: any[] = [
    {
      name: 'Jan',
      value: 1,
      selected:false
    },
    {
      name: 'Feb',
      value: 2,
      selected:false
    },
    {
      name: 'Mar',
      value: 3,
      selected:false
    },
    {
      name: 'Apr',
      value: 4,
      selected:false
    },
    {
      name: 'May',
      value: 5,
      selected:false
    },
    {
      name: 'Jun',
      value: 6,
      selected:false
    },
    {
      name: 'Jul',
      value: 7,
      selected:false
    },
    {
      name: 'Aug',
      value: 8,
      selected:false
    },
    {
      name: 'Sept',
      value: 9,
      selected:false
    },
    {
      name: 'Oct',
      value: 10,
      selected:false
    },
    {
      name: 'Nov',
      value: 11,
      selected:false
    },
    {
      name: 'Dec',
      value: 12,
      selected:false
    },
  ];

  option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          backgroundColor: '#283b56'
        }
      },
      formatter: function (params) {
        // console.info(params);
        let date = new Date();
        let month = (date.getMonth() + 1) + '-' + date.getDate();
        let day = weekday[date.getDay()];
        return month + '<br>' + day + '<br>' + '$' + params[0].value;
      }
    },
    legend: {
      show: false
    },
    toolbox: {
      show: false,
      feature: {
        dataView: { readOnly: false },
        restore: {},
        saveAsImage: {}
      }
    },
    dataZoom: [{
      show: false,
      start: 0,
      end: 100
    }],
    xAxis: [
      {
        show:true,
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun','1','2'],
        boundaryGap:true,
        axisTick:{
            show:true,
            alignWithLabel:true
        }

      },
      {
        show:false,
        type: 'category'
      }
    ],
    yAxis: [
      {
        show: false,
        type: 'value',
        scale: true
      },
      {
        show: false,
        type: 'value',
        scale: true
      }
    ],
    series: [
      {
        name: '',
        type: 'bar',
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: (function () {
          return [10,20,30,40,50,60,70,80,90];
        })(),
        itemStyle: {
          color: 'rgba(88, 174, 251, 1)'
        }
      },
      {
        name: '',
        type: 'line',
        data: (function () {
          return [10,20,30,40,50,60,70,80,90];
        })(),
        itemStyle: {
          color: '#ff890a'
        }
      },

    ]
  };

  constructor(
    public http: HttpClient
  ) {
    let month = new Date().getMonth();
    month += 1;
    let find = this.months.find(value=>value.value == month);
    // find.selected = true;
    this.selecedLi(null,find);
  }

  ngOnInit() {

  }

  scroll:any;
  initMonthScroll(){
    if(document.body.offsetWidth>=750){
      return false;
    }
    let month = new Date().getMonth()+1;
    if(month < 7){  month = 0; }
    if(month >= 7){ 
      if(document.body.offsetWidth>375){
        month = 7; 
      }else{
        month = 8;
      }
    }
    let xCoordinate = month*(-40);
    this.monthScroll.nativeElement.style.width = document.body.offsetWidth+"px";
    this.scroll = new BScroll(this.monthScroll.nativeElement, {
      // click: true,
      tap:true,
      scrollX:true,
      scrollY:false,
      scrollbar:true
    });

    this.scroll.scrollTo(xCoordinate,0,100);
    
    // let monthDoc = new Date().getMonth()+1;
    // let doc = document.getElementById('li_'+monthDoc);
    // this.scroll.scrollToElement(doc,1000,true,true);
    // this.scroll.disable();
    // console.info('this.monthScroll.nativeElement.style');
    // console.info(this.monthScroll.nativeElement.style);
    // this.monthScroll.nativeElement.style.overflowX="scroll";
    // this.monthScroll.nativeElement.style.overflowY="hidden";
  }


  selecedLi(evt,li){
    // console.info(evt);
    this.months.forEach((data)=>{
      if(data.value==li.value){
        data.selected = true;
      }else{
        data.selected = false;
      }
    });
  }

  ngAfterViewInit(): void {
    this.initChart();
    this.intPicChart();
    this.initMonthScroll();

    let scroll = {
      top: 0,
      left: 100,
      behavior: 'smooth' //  smooth(平滑滚动),instant(瞬间滚动),默认auto
    };
  }
  url = '';
  getPieData(pararms: Object | null | string) {
    this.url = '/scm/app/transactionStatisticsPie.do';
    return this.http.post(this.url, {}, this.httpOptions).toPromise();
  }

  async pieData() {
    return await this.getPieData('');
  }

  intPicChart(): void {
    let element = this.picChart.nativeElement;
    element.style.width = (document.body.clientWidth - 16) + 'px';//设置容器宽度
    let myChart = ECharts.init(element);
    const myTools =
    {
      myThis: this,
      myHttp: this.http
    }


    let pieOptins: any = {
      color: [
        '#1188ee',
        '#295ec4',
        '#27498c'
      ],
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        show: false,
        orient: 'vertical',
        left: 10,
        data: ['Clothing', 'Restaurant Food', 'Transportation']
      },
      series: [
        {
          name: 'datafrom',
          type: 'pie',
          radius: ['30%', '50%'],
          avoidLabelOverlap: false,
          minShowLabelAngle: 0,
          label: {
            show: true,
            position: 'outside',
            formatter: '${c}\n{b}'
          },
          emphasis: {
            label: {
              show: true,
              position: 'outside',
              fontSize: 10,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: true,
            smooth: 0.2,
            length: 10,
            length2: 20
          },
          itemStyle: {
            // color: '#27498c',
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          },
          data: []
          /* [
            { value: 114.12, name: 'Clothing' },
            { value: 310.62, name: 'Restaurant Food' },
            { value: 335.00, name: 'Transportation' }
          ] */
        }
      ]
    };
    myTools.myThis.pieData().then(
      (resolved: any) => {
        let dataStr = JSON.stringify(resolved);
        resolved = JSON.parse(dataStr);
        pieOptins.series[0].data = resolved.responseBody.data;
        myChart.setOption(pieOptins);
      }
    );


  }

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

  balance = 0;
  initChart(): void {
    let element = this.chart.nativeElement;
    element.style.width = (document.body.clientWidth - 16) + 'px';//设置容器宽度
    let myChart = ECharts.init(element);
    var option = this.option;
    this.url = '/scm/app/transactionStatisticsBar.do';
    this.http.post(this.url, {}, this.httpOptions).subscribe(
      (data:any)=>{
        option.xAxis[0].data=data.responseBody.xAxisNames;
        option.series[0].data=data.responseBody.barDatas;
        option.series[1].data=data.responseBody.barDatas;
        this.balance = data.responseBody.balance;
        myChart.setOption(<object>option);
      },
      (error)=>{

      }
    )

  }
}
